<?php

namespace app\service\user;
use app\admin\model\user\Assets;
use app\admin\model\user\MoneyLog;

class UserMoneyLog
{
    public static $types = [
        1 => '充值',
        3 => '管理员操作',
        4 => '会员提现',
        5 => '管理员拒绝提现，返还金额',
        6 => '余额支付',
        10 => '分销佣金',
    ];
    /**
     * 余额变动记录
     * @author mitu
     * @date   2023-11-28
     * @param  integer     $user_id      用户ID
     * @param  integer     $before_money 变动前金额
     * @param  integer    $money        变动金额
     * @param  integer    $type         变动类型
     * @param  string     $remark       备注
     * @param  string     $ordeNo       订单号
     * @return [type]                   返回
     */
    public function changeMoney($user_id, $money = 0, $type = 1, $remark = '', $ordeNo = '')
    {
        $beforeMoney = Assets::where('user_id',$user_id)->value('user_money');
        $afterMoney = bcadd($beforeMoney, $money, 2);
        //如果变动结果小于0 则返回失败
        if ($afterMoney < 0) {
            throw new \Exception('金额不足');
        }
        if ($afterMoney == $beforeMoney) {
            throw new \Exception('金额没有发生变化');
        }
        $ret = Assets::where('user_id', $user_id)->update([
            'user_money' => $afterMoney,
        ]);
        if (!$ret) {
            throw new \Exception('更新会员余额失败');
        }
        $data = array(
            'user_id' => $user_id,
            'change_money' => $money,
            'before_money' => $beforeMoney,
            'after_money' => $afterMoney,
            'change_type' => $type,
            'remark' => $remark,
            'order_sn' => $ordeNo,
            'create_time' => time()
        );
        $result = MoneyLog::create($data);
        if (!$result) {
            throw new \Exception('插入流水记录失败');
        }
        return true;
    }
}
